#include <QRegExp>

#include "FFmpeg.h"
#include "atime.h"

FFmpeg::FFmpeg(const QString &bin, QObject *parent): Converter(bin, parent),
		_threads(1)
{
	connect(this, SIGNAL(stderrLineOutput(const QString &)), this, SLOT(parseOutput(const QString &)));
}

void FFmpeg::parseOutput(const QString &line)
{
	// file length
	if (line.contains("Duration"))
	{
		//   Duration: 00:25:59.9, start: 0.000000, bitrate: 1612 kb/sline: 
		QRegExp lengthExp("(\\d{2}):(\\d{2}):(\\d{2})");
		
		if (-1 < lengthExp.indexIn(line))
		{
			_totalSecond = ATime(lengthExp.cap(1).toInt(), lengthExp.cap(2).toInt(), lengthExp.cap(3).toInt()).toSecs();
		}
	}
	// progress
	else if (line.contains("frame") && line.contains("fps") && line.contains("size") && line.contains("time"))
	{
		// frame=   24 fps=  0 q=2.0 size=      28kB time=0.7 bitrate= 315.5kbits/s    
		QRegExp elapsedExp("time=(\\d+\\.\\d)");
		
		if (-1 < elapsedExp.indexIn(line))
		{
			_currentSecond = static_cast<int>(elapsedExp.cap(1).toDouble());
			emit progressChanged(static_cast<int>(static_cast<double>(_currentSecond) / _totalSecond * 100));
		}
	}
}

void FFmpeg::convert(const QString &args)
{
	if (args.contains("-threads"))
		Converter::convert(args);
	else
		Converter::convert(args + QString(" -threads %1").arg(_threads));
}
